package com.yangjian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yangjian.bean.*;
import com.yangjian.dao.OrdersDao;
import com.yangjian.dto.OrderDto;
import com.yangjian.page.PageParameter;
import com.yangjian.service.*;
import com.yangjian.util.BaseContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Transactional
@Service
public class OrdersServiceImpl implements OrdersService {


    @Autowired
    private OrdersDao dao;


    @Autowired
    private AddressBookService addressBookService;


    @Autowired
    private UserService userService;


    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * 提交（添加）订单
     *
     * @param orders
     * @return
     */
    @Override
    public int add(Orders orders) {
        //先提交订单表，才可以得到订单表的主键id，才可以补充到订单详情表里去
        //提交订单表之前需要补充数据
        initOrder(orders);

        //添加订单表
        int row = dao.insert(orders);

        if (row>0){
            //补充订单详情表(订单详情表与购物车一样的),先利用用户id查询购物车
            List<ShoppingCart> shoppingCarts = shoppingCartService.findByUserUd(BaseContext.getCurrentId());

            int row1=0;
            //遍历得购物车的每一样商品
            for (ShoppingCart shoppingCart : shoppingCarts) {
                //创建一个新的订单详情表对象
                OrderDetail orderDetail = new OrderDetail();
                //把购物车的数据拷贝到订单详情表里
                BeanUtils.copyProperties(shoppingCart,orderDetail);
                orderDetail.setId(null);
                //把订单id添加进去
                orderDetail.setOrderId(orders.getId());

                //执行添加订单详情信息
                row1 += orderDetailService.add(orderDetail);

            }

            System.out.println("row1 = " + row1);
            return row1==shoppingCarts.size()?1:0;
        }

        System.out.println("row = " + row);
        return row;
    }

    /**
     * 订单分页查询
     *
     * @param parameter
     * @return
     */
    @Override
    public IPage<OrderDto> findPage(PageParameter parameter,long uid) {
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId,uid);
        IPage<Orders> page =new Page<>(parameter.getPage(),parameter.getPageSize());
        IPage<Orders> page1 = dao.selectPage(page, lqw);
       List<OrderDto> list= page1.getRecords().stream().map(orders -> {
            //用订单id查询订单详情
            List<OrderDetail> orderDetailList = orderDetailService.findByOrderId(orders.getId());
            //创建一个OrderDto
            OrderDto orderDto = new OrderDto();
            //把订单添加到orderDto
            orderDto.setOrderDetails(orderDetailList);
            //把订单拷贝进去
            BeanUtils.copyProperties(orders,orderDto);

            //返回orderDto
            return orderDto;
        }).collect(Collectors.toList());

       IPage<OrderDto> page2=new Page<>();
       page2.setRecords(list);
       page2.setTotal(page1.getTotal());
        return page2;
    }

    /**
     * 服务端订单分页查询
     *
     * @param parameter
     * @return
     */
    @Override
    public IPage<OrderDto> findPage1(PageParameter parameter) {
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        System.out.println("parameter.getNumber() = " + parameter.getNumber());
        lqw.like(parameter.getNumber()!=null,Orders::getNumber,parameter.getNumber());
        if (parameter.getBeginTime()!=null){
            if (parameter.getEndTime()!=null){
                lqw.between(Orders::getOrderTime,parameter.getBeginTime(),parameter.getEndTime());
            }
        }
        IPage<Orders> page =new Page<>(parameter.getPage(),parameter.getPageSize());
        IPage<Orders> page1 = dao.selectPage(page, lqw);
        List<OrderDto> list= page1.getRecords().stream().map(orders -> {
            //用订单id查询订单详情
            List<OrderDetail> orderDetailList = orderDetailService.findByOrderId(orders.getId());
            //创建一个OrderDto
            OrderDto orderDto = new OrderDto();
            //把订单添加到orderDto
            orderDto.setOrderDetails(orderDetailList);
            //把订单拷贝进去
            BeanUtils.copyProperties(orders,orderDto);

            //返回orderDto
            return orderDto;
        }).collect(Collectors.toList());

        IPage<OrderDto> page2=new Page<>();
        page2.setRecords(list);
        page2.setTotal(page1.getTotal());
        return page2;
    }

    /**
     * 根据id修改订单
     *
     * @param orders
     * @return
     */
    @Override
    public int update(Orders orders) {

        Orders order = dao.selectById(orders.getId());
        order.setStatus(orders.getStatus());
        int row = dao.updateById(order);

        return row;
    }


    private void initOrder(Orders orders) {
        //补充订单编号
        orders.setNumber(UUID.randomUUID().toString().replace("-", " "));
        //补充订单的状态：1：待付款
        orders.setStatus(2);
        //补充用户id
        orders.setUserId(BaseContext.getCurrentId());
        //补充下单时间
        orders.setOrderTime(LocalDateTime.now());
        //补充付款时间
        orders.setCheckoutTime(LocalDateTime.now());
        //补充收件人的电话(根据地址谱id查询用户电话)
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        //补充收件人的地址
        String address = (addressBook.getProvinceName() != null ? addressBook.getProvinceName() : "")
                + (addressBook.getCityName() != null ? addressBook.getCityName() : "")
                + (addressBook.getDistrictName() != null ? addressBook.getDistrictName() : "")
                + (addressBook.getDetail() != null ? addressBook.getDetail() : "");

        orders.setAddress(address);
        //补充用户名字
        User user = userService.findById(BaseContext.getCurrentId());
        orders.setUserName(user.getName());
        //补充收件人名字
        orders.setConsignee(addressBook.getConsignee());
    }


}
